package com.nannybear.Communication;

import android.util.Log;

import com.nannybear.Model.Command;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @brief Receive message from NannyBear.
 */
public class Postman extends Thread{
    /********** DECLARATIONS **********/
    private String receivedMessage = null;
    private String messageStock[];
    private Connection connection;
    private ArrayList<Command> commands = new ArrayList<>();

    /************ METHODS ************/
    /**
     * @brief Constructor.
     */
    public Postman(Connection connection){
        this.connection = connection;
        this.commands.add(Protocol.TEMP_VALUE, this.connection.getActivity().getTemperatureChange());
        this.commands.add(Protocol.LIGHT_STATE, this.connection.getActivity().getBrightnessChange());
        this.commands.add(Protocol.HUM_VALUE, this.connection.getActivity().getHumidityChange());
        this.commands.add(Protocol.BABY_STATE, this.connection.getActivity().getBabyStateChange());
        this.commands.add(Protocol.HUM_THRESHOLD, this.connection.getActivity().getHumidityThresholdChange());
        this.commands.add(Protocol.TEMP_THRESHOLD, this.connection.getActivity().getTemperatureThresholdChange());
    }

    /**
     * @brief decode the nex message.
     */
    public void decodeMessage(String receivedMessage){
        Log.e("Postman","msg received:"+receivedMessage);
        this.messageStock = receivedMessage.split("/");
        if((messageStock[0] != null)&&(messageStock[1]!=null)){
            try{
                this.commands.get(Integer.parseInt(messageStock[0])).execute(messageStock[1]);
            }catch (NumberFormatException ex){
                ex.getMessage();
            }
        }
    }

    /**
     * @brief thread for the reception.
     */
    public void run(){
        while(connection.isConnected()){
            try{
                while(connection.getSocket().getInputStream().available() == 0){
                    Thread.sleep(500);
                }
                receivedMessage = connection.read();
                if(receivedMessage.length()>0){
                    decodeMessage(receivedMessage);
                }
            }catch (IOException ex){
                Log.e("Postman", "Problem with the reception : "+ex.getMessage());
            }catch (InterruptedException ex){
                Log.e("Postman", "Interrupted task : "+ex.getMessage());
            }
        }
        Log.e("Postman", "Connection lost");
    }

    /*********** ACCESSORS ***********/
}
